//深拷贝
export function cloneDeep(obj) {
    if (!obj && typeof obj !== "object") {
        throw new Error("error arguments");
    }
    const targetObj = Array.isArray(obj) ? [] : {};
    for (let key in obj) {
        //只对对象自有属性进行拷贝
        if (obj.hasOwnProperty(key)) {
            if (obj[key] && typeof obj[key] === "object") {
                targetObj[key] = cloneDeep(obj[key]);
            } else {
                targetObj[key] = obj[key];
            }
        }
    }
    return targetObj;
}

//清空对象的空值
export function removeEmptyObj(obj) {
    Object.keys(obj).forEach((item) => {
        if (obj[item] === "" || obj[item] === undefined || obj[item] === null || obj[item] === "null") delete obj[item];
    });
    return obj;
}

//防抖
export function debounce(func, delay) {
    let timer = null;
    console.log(func);
    return function (...args) {
        console.log(timer);
        if (timer) clearTimeout(timer);
        timer = setTimeout(() => {
            func.apply(this, args);
        }, delay);
    };
}

//生成随机数16进制
export function color16() {
    const r = Math.floor(Math.random() * 256);
    const g = Math.floor(Math.random() * 256);
    const b = Math.floor(Math.random() * 256);
    const color = `#${r.toString(16)}${g.toString(16)}${b.toString(16)}`;
    return color;
}

// 导出页面为PDF格式
import jsPDF from "jspdf";
import html2canvas from "html2canvas";

class PdfLoader {
    constructor(ele, pdfFileName) {
        this.ele = ele;
        this.pdfFileName = pdfFileName;
    }

    getPDF() {
        html2canvas(this.ele, {
            useCORS: true,
            scale: 2
        }).then((canvas) => {
            const contentWidth = canvas.width / 2;
            const contentHeight = canvas.height / 2;
            const pdf = new jsPDF("", "pt", [contentWidth, contentHeight]);
            const pageData = canvas.toDataURL("image/jpeg", 1.0);

            pdf.addImage(pageData, "JPEG", 20, 0, contentWidth - 40, contentHeight);
            pdf.save(`${this.pdfFileName}.pdf`);
        });
    }
}

export default PdfLoader;
